package com.icss.servlets;

import java.io.File;
import java.io.IOException;
import java.util.Iterator;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;


/**
 * @author 韦锦良
 *　类的作用：文件上传类，专门用于对发表的文章进行图片上传
 * 最后修改时间：2010-3-13　下午03:56:35
 * 最后的改动内容：初始版本
 */
@SuppressWarnings("serial")
public class UploadServlet extends HttpServlet {

	public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

		doPost(request, response);

	}

	public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

		//创建一个文件仓库，用于将上传的文件暂时性的保存
		FileItemFactory factory = new DiskFileItemFactory();
		
		//用于处理网页中的上传组件
		ServletFileUpload upload = new ServletFileUpload(factory);

		//将上传的文件保存到指定的目录里面去
		try {
			List items = upload.parseRequest(request);
			Iterator iter = items.iterator();
			while (iter.hasNext()) {
				FileItem item = (FileItem) iter.next();
				String fileName = getFileName(item.getName());
				if (!isAcceptType(fileName)) {
					response.getWriter().print("{failure:'true'}");
					break;
				}

				File uploadedFile = new File(fileName);
				item.write(uploadedFile);

				response.getWriter().print("{success:'true',fileURL:'" + getResponseURL(fileName) + "'}");
			}

		} catch (FileUploadException e) {
			e.printStackTrace();
		} catch (Exception e) {
			e.printStackTrace();
		}

	}

	
	//随机生成一个文件名，利用系统的当前毫秒数
	public String getFileName(String fileName) {

		String uploadPath = getServletContext().getRealPath("/") + "upload";
		String fileType = fileName.substring(fileName.lastIndexOf("."));
		return uploadPath + "\\" + System.currentTimeMillis() + fileType;

	}

	//生成向客户端返回的图片地址
	public String getResponseURL(String fileName) {

		return fileName.substring(fileName.lastIndexOf("\\") + 1);

	}

	//判断是否是合法的图片文件
	public boolean isAcceptType(String fileName) {

		String type = fileName.substring(fileName.lastIndexOf(".") + 1);

		if ("jpg".equalsIgnoreCase(type) || "gif".equalsIgnoreCase(type) || "jpeg".equalsIgnoreCase(type)
				|| "png".equalsIgnoreCase(type) || "bmp".equalsIgnoreCase(type)) {

			return true;
		}

		return false;
	}
}